package org.lg.multidatabase.config;

import lombok.extern.slf4j.Slf4j;
import org.lg.multidatabase.enumeration.DataSourceKeyEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: DynamicDataSource
 * @Author: lvgang
 * @Date: 2022/4/24 10:03
 * @Description: 动态DataSource注入类
 */
@Component
@Primary    //该Bean设置为主入Bean
@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {

    public static ThreadLocal<Integer> dataSourceKey = new ThreadLocal<>();

    @Autowired
    DataSource dataSourceOne;

    @Autowired
    DataSource dataSourceTwo;

    /**
     * 获取当前数据库标识
     * @return
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return dataSourceKey.get();
    }

    /**
     * 初始化targetDataSources
     */
    @Override
    public void afterPropertiesSet() {
        log.info("=====Start===DynamicDataSource===afterPropertiesSet===");
        //设置所有的数据源
        Map<Object,Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceKeyEnum.ONE.getIndex(),dataSourceOne);
        targetDataSources.put(DataSourceKeyEnum.TWO.getIndex(),dataSourceTwo);
        super.setTargetDataSources(targetDataSources);
        log.info("=====DynamicDataSource===Number==={}",targetDataSources.size());
        //设置默认的数据源
        super.setDefaultTargetDataSource(dataSourceOne);
        super.afterPropertiesSet();
    }
}
